package algorithms;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查找相同key 的元素 并算出来value总和 与参照对比
 */
public class SearchList {
    public static void main(String[] args) {
        SearchBean b1 = new SearchBean();
        SearchBean b2 = new SearchBean();
        SearchBean b3 = new SearchBean();
        b1.setCode(1);
        b1.setNumber(2);
        b1.setTotal(5);
        b2.setCode(1);
        b2.setNumber(2);
        b2.setTotal(5);
        b3.setCode(3);
        b3.setNumber(2);
        b3.setTotal(5);
        List<SearchBean> list = new ArrayList<>();
        list.add(b1);
        list.add(b2);
        list.add(b3);
        search2(list);
    }

    /**
     * 方式一
     *
     * @param data
     */
    public static void search(List<SearchBean> data) {
        int sum = 0;
        for (int i = 0; i < data.size(); i++) {
            SearchBean current = data.get(i);
            sum = current.getNumber();
            for (int j = 1; j < data.size(); j++) {
                if (current.code == data.get(j).code) {
                    sum += data.get(j).getNumber();
                }
            }
        }
        System.out.println(sum);
    }

// 1   10
// 2   5
// 1   30

    /**
     * 方式二：使用map 分别做两个操作
     * @param data
     */
    public static void search2(List<SearchBean> data) {
        HashMap<Integer, Integer> sumMap = new HashMap();
        HashMap<Integer, Integer> reaMap = new HashMap();

        //遍历 对需要累加的map进行计算
        for (SearchBean currentItem : data) {
            if (sumMap.containsKey(currentItem.getCode())) {
                int itemCount = sumMap.get(currentItem.getCode()) + currentItem.getNumber();
                sumMap.put(currentItem.getCode(), itemCount);
            } else {
                sumMap.put(currentItem.getCode(), currentItem.getNumber());
            }
        }

        //reaMap.put(currentItem.getCode(),currentItem.getTotal());

        //用于对比的map
        for (SearchBean currentItem : data) {
            reaMap.put(currentItem.getCode(), currentItem.getTotal());
            if (sumMap.get(currentItem.getCode()) != reaMap.get(currentItem.getCode())) {
                System.out.println("数量不匹配！");
                return;
            }
        }
    }
}

class SearchBean {
    int code;
    int number;
    int total;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}